package com.qf.merchant.shiro;



import com.qf.common.response.ResponseEnum;
import com.qf.entity.dto.Admin;
import com.qf.entity.dto.Merchant;
import com.qf.entity.po.LoginAdmin;
import com.qf.entity.po.LoginMerchant;
import com.qf.service.AdminService;
import com.qf.service.MerchantService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm
 */
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private MerchantService merchantService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }

    /**
     * 登录验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        Merchant merchant = merchantService.getByUserNamePwd(username,password);
        if (merchant == null) {
            throw new RuntimeException(ResponseEnum.LOGIN_FAIL.getMessage());
        }
        LoginMerchant loginMerchant = new LoginMerchant();
        loginMerchant.setId(merchant.getId());
        loginMerchant.setName(merchant.getName());
        loginMerchant.setPhone(merchant.getPhone());
        loginMerchant.setQq(merchant.getQq());
        loginMerchant.setWechat(merchant.getWechat());
        loginMerchant.setCreateTime(merchant.getCreateTime());
        return new SimpleAuthenticationInfo(loginMerchant,merchant.getPassword(),merchant.getUsername());
    }
}
